#include <string>
#include <iostream>

#include "data_store.h"
#include "section_item.h"

using namespace std;

Section_item::Section_item(string name) :
  Item(name)
{
  _type = section;
}

Section_item::~Section_item()
{
  for (int i = 0; i < (int) _items.size(); ++i) {
    delete _items[i];
  }
}

void Section_item::add_item(Item *item)
{
  _items.push_back(item);
  _count++;
}

Item *Section_item::get_item_deep(string name)
{
  vector<string> sections = Data_store::tokenize(name, "/");
  Item *new_item = get_item(sections[0]);
  while (sections.size() > 1 && new_item != NULL) {
    // delete the first element
    sections.erase(sections.begin());
    new_item = new_item->get_item(sections[0]);
  }
  return new_item;
}

Item *Section_item::get_item(string name)
{
  for (int i = 0; i < (int) _items.size(); ++i) {
    //cout << "Search " << i << " " << name << " " << _items[i]->get_name() << endl;
    if (_items[i]->get_name() == name) {
      return _items[i];
    }
  }
  return NULL;
}

void Section_item::delete_item(string name)
{
  for (int i = 0; i < (int) _items.size(); ++i) {
    if (_items[i]->get_name() == name) {
      delete _items[i];
      _items.erase(_items.begin()+i);
      --_count;
      return;
    }
  }
  cout << "ERROR: Item not found, " << name << endl;
}

void Section_item::clear(void)
{
  _count = 0;
  for (int i = 0; i < (int) _items.size(); ++i) {
    delete _items[i];
  }
  _items.clear();
}

void Section_item::save(ostream &os, string indent)
{
  os << indent << "[ BEGIN \"" << get_name() << "\" ] " << _items.size()
      << endl;
  for (int i = 0; i < (int) _items.size(); ++i) {
    _items[i]->save(os, indent + "  ");
  }
  os << indent << "[ END \"" << get_name() << "\" ]" << endl;
}
